#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author： 青城子
# datetime： 2022/4/16 21:33
# ide： PyCharm

from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator  # 用户对同一商品重复点击收藏

from .models import UserFav, UserLeavingMessage, UserAddress
from apps.goods.serializers import GoodsSerializer

"""
两种方式限制重复收藏
方法1：models中class Meta 中 设置 unique_together = ("user", "goods") 
方法2：serializers的Meta中validators实现
两个方法都设置时已方法2为准
"""


class UserFavDetailSerializer(serializers.ModelSerializer):
    goods = GoodsSerializer()

    class Meta:
        model = UserFav
        fields = ["goods", "id"]


class UserFavSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )  # 当前用户收藏

    # user是外键关系,删除收藏时需要返回id
    class Meta:
        model = UserFav
        validators = [
            UniqueTogetherValidator(
                queryset=UserFav.objects.all(),
                fields=["user", "goods"],
                message="已经收藏"
            )
        ]

        fields = ["user", "goods", "id"]


class LeavingMessageSerializers(serializers.ModelSerializer):
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    # 只返回add_time字段，不能提交该字段
    add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M')

    class Meta:
        model = UserLeavingMessage
        fields = ["user", "message_type", "subject", "message", "file", "id", "add_time"]


class AddressSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M')

    class Meta:
        model = UserAddress
        fields = ["id", "user", "province", "city", "district", "address", "signer_name", "add_time", "signer_mobile"]
